<!-- 客户管理-客户信息-客户跟进记录 -->
<template>
  <div class="client-follow-record">
    <a-space
      :style="{
        marginBottom: '10px',
      }"
    >
      <a-button
        :style="{
          height: '40px',
        }"
        type="primary"
        @click="isShowModalBtn"
      >
        <template #icon>
          <icon-plus></icon-plus>
        </template>
        <template #default> 新增跟进记录 </template>
      </a-button>
    </a-space>

    <TableTurn
      ref="tableRef"
      :isShowPagination="false"
      :tableData="getData"
      :args="args"
    >
      <a-table-column :width="70" align="center">
        <template #title> 序号 </template>
        <template #cell="{ rowIndex }">
          {{ rowIndex + 1 }}
        </template>
      </a-table-column>

      <a-table-column
        title="拜访人员"
        dataIndex="visitors"
        align="center"
        :width="120"
      ></a-table-column>
      <!-- <a-table-column
        title="参与人"
        dataIndex="personName"
        align="center"
        :width="300"
      >
      </a-table-column> -->
      <a-table-column
        title="沟通方式"
        dataIndex="communicateWay"
        align="center"
        :width="120"
      >
        <template #cell="{ record }">
          {{ record.communicateWay === '0' ? '线上沟通' : '线下拜访' }}
        </template>
      </a-table-column>
      <a-table-column
        title="推进成效"
        dataIndex="effect"
        align="center"
        :width="120"
      >
        <!-- <template #cell="{ record }">
          {{ (props.stateList[record.state - 1] as any).name }}
        </template> -->
      </a-table-column>
      <a-table-column
        :sortable="sortableArgs"
        title="下次跟进时间"
        dataIndex="nextFollowTime"
        align="center"
        :width="300"
      >
        <template #cell="{ record }">
          {{
            record.nextFollowTime === 0
              ? '暂无跟进时间'
              : dayjs(record.nextFollowTime).format('YYYY-MM-DD HH:mm:ss')
          }}
        </template>
      </a-table-column>

      <a-table-column
        :sortable="sortableArgs"
        title="创建时间"
        dataIndex="createdTime"
        align="center"
        :width="300"
      >
        <template #cell="{ record }">
          {{ dayjs.unix(record.createdTime).format('YYYY-MM-DD HH:mm:ss') }}
        </template>
      </a-table-column>

      <!-- 操作item -->
      <a-table-column align="center" :width="100" fixed="right" title="操作">
        <template #cell="{ record, rowIndex }">
          <a-tooltip content="查看详情">
            <IconFont
              type="icon-details-def"
              :size="26"
              :style="{
                marginRight: '10px',
                cursor: 'pointer',
              }"
              @click="goDetail(record)"
            />
          </a-tooltip>
          <a-tooltip content="删除">
            <a-popconfirm
              content="确认删除？"
              type="error"
              @ok="deleteItem(record.id, rowIndex)"
            >
              <IconFont
                type="icon-delete"
                :size="26"
                :style="{
                  marginRight: '10px',
                  cursor: 'pointer',
                }"
              />
            </a-popconfirm>
          </a-tooltip>
        </template>
      </a-table-column>
    </TableTurn>

    <addFollowModal
      :stateList="stateList"
      v-model:visible="modalVisible"
      :client-name="clientName"
      :form-detail="currDetail"
      :type="currType"
      @addRecordEmit="addRecordEmit"
    >
    </addFollowModal>
  </div>
</template>

<script lang="ts" setup>
  import { reactive, ref, watchEffect } from 'vue';
  import { useRoute } from 'vue-router';
  import { useOrderStore } from '@/store';
  import {
    GetClientDetailTabs,
    PostClientDetailRecord,
    DelClientDetailRecord,
  } from '@/api/order-management/client-management/client-list';
  import { IClientAddFollowRecord } from '@/types/order';
  import dayjs from 'dayjs';
  import addFollowModal from './components/add-follow-modal/index.vue';

  const props = withDefaults(
    defineProps<{
      clientName: string; // 客户名称
      stateList: any; // 状态列表
    }>(),
    {}
  );

  const route = useRoute();
  const store = useOrderStore();
  let clientId = Number(route.query.id);

  // 表格是否可以排序
  let sortableArgs = reactive({
    sortDirections: ['ascend', 'descend'],
  });
  // 表格配置
  const args = reactive({
    stripe: true,
    scroll: {
      y: 500,
    },
    bordered: {
      headerCell: true,
    },
  });

  let currDetail = ref<IClientAddFollowRecord>({
    visitors: '', // 拜访联系人
    followStateId: [], // 参与人
    communicateWay: '0', // 沟通方式， 0为线上沟通，1为线下拜访
    communicationTime: '', // 沟通时间
    communicationMatters: '', // 沟通事项
    state: 2, // 推进成效
    summary: '', // 跟进与维护总结
    nextFollowTime: 0, // 下次跟进时间
    nextFollowContent: '', // 下次跟进内容
  });

  let currType = ref('add'); // 判断用户是新增还是查看详情
  let tableRef = ref(); // 储存table的ref
  let currStateIndex = ref(); // 储存最新的状态的index
  let data = ref();
  // 获取跟进记录数据
  const getData = async (pageData?: any) => {
    try {
      const res = await GetClientDetailTabs({
        id: clientId,
        typeId: 0,
        pageData: {
          page: 0,
          size: -1,
        },
      });
      res.forEach((item) => {
        let msg = props.stateList.filter((i) => i.id === item.state);
        if (msg.length === 0) return;
        if (msg) item.effect = msg[0].name;
      });
      return Promise.resolve(res);
    } catch (err: unknown) {
      console.log(err);
    }
  };

  let modalVisible = ref(false); // 判断是否显示弹出框

  // 是否显示对话框
  const isShowModalBtn = () => {
    currType.value = 'add';

    // 初始化currDetail
    currDetail.value = {
      visitors: '', // 拜访联系人
      followStateId: [], // 参与人
      communicateWay: '0', // 沟通方式， 0为线上沟通，1为线下拜访
      communicationTime: '', // 沟通时间
      communicationMatters: '', // 沟通事项
      state: 2, // 推进成效
      summary: '', // 跟进与维护总结
      nextFollowTime: 0, // 下次跟进时间
      nextFollowContent: '', // 下次跟进内容
    };
    modalVisible.value = true;
  };
  // 去往详情页面
  const goDetail = (record: any) => {
    currType.value = 'readOnly';
    currDetail.value = record;
    modalVisible.value = true;
  };

  // 新增跟进记录自定义事件
  const addRecordEmit = async (form: IClientAddFollowRecord) => {
    store.currState = form.state;
    let data: any = form;
    data.stateId = (props.stateList[form.state - 1] as any).id;
    data.customerId = clientId;
    data.nextFollowTime = Number(data.nextFollowTime);
    delete data.state;
    try {
      await PostClientDetailRecord(data);
      tableRef.value.loadData();
    } catch (err: unknown) {
      console.log(err);
    }
  };

  // 删除一项跟进记录
  const deleteItem = async (id: number, rowIndex: number) => {
    try {
      await DelClientDetailRecord({
        id,
      });
      tableRef.value.tableList.splice(rowIndex, 1);
    } catch (err: unknown) {
      console.log(err);
    }
  };

  // onMounted(()=>{

  // })

  defineExpose({ currStateIndex }); // 将变化的状态给export出去
</script>

<style scoped lang="less">
  .client-follow-record {
    padding: 0px 20px;
  }

  :deep(.arco-space) {
    width: 100%;
    display: flex;
    flex-direction: row-reverse;
  }
</style>
